#!/bin/bash
set -e

echo "===== PostgreSQL pgBackRest 备份状态检查 ====="
echo ""

# 检查是否运行在备份服务器上
if docker ps | grep -q "pgbackrest-serverA"; then
  SERVER_TYPE="备份服务器 (A)"
elif docker ps | grep -q "pgbackrest-serverB"; then
  SERVER_TYPE="还原服务器 (B)"
else
  SERVER_TYPE="未知"
fi

echo "当前服务器类型: $SERVER_TYPE"
echo ""

# 检查pgBackRest配置和状态
echo "1. pgBackRest 配置检查:"
if [ "$SERVER_TYPE" == "备份服务器 (A)" ]; then
  docker exec pgbackrest-serverA pgbackrest --stanza=poddb check
else
  docker exec pgbackrest-serverB pgbackrest --stanza=poddb check
fi

echo ""
echo "2. 备份信息摘要:"
if [ "$SERVER_TYPE" == "备份服务器 (A)" ]; then
  docker exec pgbackrest-serverA pgbackrest --stanza=poddb info
else
  docker exec pgbackrest-serverB pgbackrest --stanza=poddb info
fi

# 在备份服务器上检查MinIO存储情况
if [ "$SERVER_TYPE" == "备份服务器 (A)" ]; then
  echo ""
  echo "3. MinIO 存储桶信息:"
  echo "   检查 'pgbackups' 存储桶状态..."
  
  if ! docker exec -it minio-init-serverA /usr/bin/mc ls myminio/pgbackups > /dev/null 2>&1; then
    echo "   警告: 无法访问 'pgbackups' 存储桶，请检查 MinIO 状态"
  else
    echo "   'pgbackups' 存储桶可访问"
    
    # 获取存储桶使用情况
    echo ""
    echo "4. 备份文件使用的存储空间:"
    docker exec -it minio-init-serverA /usr/bin/mc du myminio/pgbackups
    
    # 列出最近的备份文件
    echo ""
    echo "5. 存储桶文件结构(仅显示顶级目录):"
    docker exec -it minio-init-serverA /usr/bin/mc ls myminio/pgbackups
  fi
fi

echo ""
echo "===== 检查完成 =====" 